package com.axonactive.yolo.service.implement;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.axonactive.yolo.dao.interfaces.CountryRepository;
import com.axonactive.yolo.domain.Country;
import com.axonactive.yolo.exception.CountryNotFoundException;
import com.axonactive.yolo.service.interfaces.CountryService;
import com.axonactive.yolo.util.CONSTANTS;

@Service
public class CountryServiceImpl implements CountryService {
	@Resource
	private CountryRepository countryRepository;
	
	@Override
//	@CacheEvict(value="listCountryCache", allEntries = true)
	public List<Country> findAll() {
		return countryRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor = CountryNotFoundException.class)
	public void delete(int id) throws IllegalArgumentException {
		countryRepository.delete(id);
	}

	@Override
	public Country create(Country country) {
		return countryRepository.save(country);
	}

	@Override
	public Country update(Country country) {
		return countryRepository.save(country);
	}

	@Override
	public String getCurrencyCodeFromCountryCode(String countryCode) {
		String currencyCode = "";
		List<Country> countries = countryRepository.findByCountryCode(countryCode);
		if (countries.size() == 0) {
			currencyCode = CONSTANTS.DEFAULT_CURRENCY;
		} else {
			currencyCode = countries.get(0).getCurrencyCode();
		}
		return currencyCode;
	}

	@Override
	public String getCurrencyCodeFromCountryName(String countryName) {
		String currencyCode = "";
		List<Country> countries = countryRepository.findByCountryName(countryName);
		if (countries.size() == 0) {
			currencyCode = CONSTANTS.DEFAULT_CURRENCY;
		} else {
			currencyCode = countries.get(0).getCurrencyCode();
		}
		return currencyCode;
	}

	@Override
	public String getCountryCodeFromCurrencyCode(String currencyCode) {
		List<Country> countries = countryRepository.findAll();
		for (Iterator iterator = countries.iterator(); iterator.hasNext();) {
			Country country = (Country) iterator.next();
			if (country.getCurrencyCode().contains(currencyCode))
				return country.getCountryCode();
		}
		return "";
	}
}
